package com.atguigu.gulimall.seckill.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizErrorCode;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Controller
@Slf4j
public class SeckillController {

    @Autowired
    private SeckillService seckillService;

    @GetMapping("/currentSeckillSkus")
    @ResponseBody
    public R getCurrentSkus() {
        List<SeckillSkuRedisTo> data = seckillService.getSeckillSkusByTs(new Date().getTime(), true);
        return R.ok().setData(data);
    }


    @GetMapping("/test")
    @SentinelResource(value = "/test1", blockHandler = "exceptionHandler", fallback = "helloFallback")
    @ResponseBody
    public R test() {
        log.info("test ......");
        return R.ok().setData(System.currentTimeMillis());
    }

    // Fallback 函数，函数签名与原函数一致或加一个 Throwable 类型的参数.
    public R exceptionHandler() {
        return R.error(BizErrorCode.PHONE_EXIST_ERROR);
    }

    public static R helloFallback() {
        return R.error(BizErrorCode.USERNAME_EXIST_ERROR);
    }



    @GetMapping("/seckill/sku/{skuId}")
    @ResponseBody
    public R getSkuSeckillInfo(@PathVariable("skuId") Long skuId) {
        SeckillSkuRedisTo data = seckillService.getSkuSeckillInfo(skuId);
        return R.ok().setData(data);
    }

    /**
     * http://seckill.gulimall.com/killl/${killId}/${num}/${key}
     *
     * @param killId 场次+skuId
     * @return
     */
    @GetMapping("/kill/{killId}/{num}/{key}")
    public String kill(@PathVariable("killId") String killId, @PathVariable("num") Long num, @PathVariable("key") String key, Model model) {

        Object data = seckillService.killSkuItem(killId, num, key);
        R r;
        if (data instanceof BizErrorCode) {
            r = R.error((BizErrorCode) data);
        } else {
            r = R.ok().setData(data);
        }

        model.addAttribute("r", r);
        return "success";
    }
}
